<template>
  <div>
    <myDivider name="车辆管理"></myDivider>
    <div class="Top">
      <el-select style="width: 110px" v-model="keyType" placeholder="请选择搜索类型">
        <el-option label="车牌号" value="licensePlateNumber"></el-option>
        <el-option label="车主" value="name"></el-option>
        <el-option label="手机号码" value="phoneNumber"></el-option>
      </el-select>
      <el-input style="width: 170px;margin-left: -5px;" v-model="keyWords" placeholder="根据关键词搜索"
        @keyup.enter.native="getTableList" clearable></el-input>
      <el-date-picker style="width: 250px;margin-left: 20px;" value-format="yyyy-MM-dd" v-model="keyTime"
        type="daterange" range-separator=" " start-placeholder="创建时间" end-placeholder="请选择时间段" @change="getTableList">
      </el-date-picker>
      <el-button type="primary" style="margin-top: 20px; margin-left: 15px" @click="SouSuo">查询</el-button>
      <el-button style="margin-top: 20px; margin-left: 15px" @click="reset">重置</el-button>
      <div class="operation">
        <el-button type="primary" @click="addClick">新增</el-button>
      </div>
    </div>

    <el-table class="tableBox" :data="TableData" style="width: 100%">
      <el-table-column align="center" prop="name" label="车辆照片" width="100px">
        <template slot-scope="scope">
          <el-image style="width: 80px; height: 60px" :src="scope.row.carImageUrl"
            :preview-src-list="[scope.row.carImageUrl]">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="licensePlateNumber" label="车牌号" width="100px">
      </el-table-column>
      <el-table-column align="center" prop="brandModel" label="品牌型号" width="150px">
      </el-table-column>
      <el-table-column align="center" prop="carType" label="车型">
      </el-table-column>
      <el-table-column align="center" prop="carColor" label="车辆颜色" width="120px">
      </el-table-column>
      <el-table-column align="center" prop="name" label="车主姓名" width="120px">
      </el-table-column>
      <el-table-column align="center" prop="phoneNumber" label="手机号码" width="150px">
      </el-table-column>
      <el-table-column align="center" prop="createTime" label="创建时间" width="180px">
      </el-table-column>
      <el-table-column align="center" label="操作" width="150px">
        <template slot-scope="scope">
          <div class="textBtn">
            <el-row>
              <el-col class="el" :span="8">
                <span style="color: #5fadff;cursor: pointer;font-weight: 600;" @click="updateClick(scope.row)">编辑</span>
              </el-col>
              <el-col class="el" :span="8">
                <span style="color: #5fadff;cursor: pointer;font-weight: 600;" @click="detailClick(scope.row)">详情</span>
              </el-col>
              <el-col class="el" :span="8">
                <span style="color: #5fadff;cursor: pointer;font-weight: 600;" @click="deleteClick(scope.row)">删除</span>
              </el-col>
            </el-row>
          </div>
        </template>
      </el-table-column>
    </el-table>



    <!-- 新增弹窗车辆 -->
    <el-dialog :close-on-click-modal="false"  width="550px" :title="AddCarPopScene === 'add' ? '新增车辆' : '修改车辆'"
      :visible.sync="AddCarPopShow" class="dialogStyle">
      <el-divider></el-divider>

      <el-form :model="insertForm" :rules="insertRules" ref="insertForm" label-width="120px">

        <el-form-item label="车牌号:" prop="licensePlateNumber">
          <el-input :disabled="AddCarPopScene == 'update'" placeholder="请输入车牌号" maxlength="10"
            v-model="insertForm.licensePlateNumber" style="width: 300px"></el-input>
        </el-form-item>
        
        <el-form-item label="选择车主:" prop="" required>
          <el-button :disabled="insertForm.hasCarSpace" @click="toSelectCarPeople">选择</el-button>
          <el-input placeholder="请选择车主" disabled maxlength="10" v-model="insertForm.populationInformationName"
            style="width: 225px"></el-input>
        </el-form-item>

        <el-form-item label="品牌型号:">
          <el-input placeholder="请输入品牌型号" maxlength="10" v-model="insertForm.brandModel"
            style="width: 300px"></el-input>
        </el-form-item>

        <el-form-item label="车型:">

          <div v-if="updateCascader" style="display: flex;justify-content: space-between;width: 300px;">
            <el-input disabled v-model="insertForm.carType" style="width: 220px;"></el-input>
            <el-button type="primary" @click="updateCascader = false">编辑</el-button>
          </div>
          <el-cascader v-else ref="cascader" style="width: 300px" v-model="insertForm.carTypeId" :props="props"
            @change="carTypeChange" placeholder="请选择车型"></el-cascader>
        </el-form-item>


        <el-form-item label="车辆颜色:">
          <el-input placeholder="请输入车辆颜色" maxlength="10" v-model="insertForm.carColor" style="width: 300px"></el-input>
        </el-form-item>

    

        <el-form-item label="车辆图片:">
          <MyUploadImgNotDetele :canUploadNum="1" :id="UploadId" v-if="ImgFileShow" :EchoImgList="EchoImgList1"
            @getImgList="getImgList1" @deleteImgList="deleteImgList1"
            uploadUrl="/business/carManage/uploadImg"> </MyUploadImgNotDetele>
        </el-form-item>

        <el-form-item label="行驶证图片:">
          <MyUploadImgNotDetele :canUploadNum="1" :id="UploadId" v-if="ImgFileShow" :EchoImgList="EchoImgList2"
            @getImgList="getImgList2" @deleteImgList="deleteImgList2"
            uploadUrl="/business/carManage/uploadImg"></MyUploadImgNotDetele>
        </el-form-item>
      </el-form>
      <el-divider></el-divider>
      <div slot="footer" style="display: flex;justify-content: space-evenly;align-items: center;height: 60px;">
        <el-button @click="AddCarPopShow = false">取消</el-button>
        <el-button type="primary" @click="okAddCarPop">确定</el-button>
      </div>

    </el-dialog>


    <!-- 选择车主弹窗 -->
    <el-dialog class="dialogStyle" :close-on-click-modal="false" width="600px" title="选择车主"
      :visible.sync="selectCarPeoplePopShow">
      <el-divider></el-divider>
      <div style="display: flex;justify-content: space-between;margin: 20px 0;">
        <el-input size="medium" style="width: 200px;" v-model="selectCarPeoplePopKeyName"
          placeholder="根据用户姓名搜索"></el-input>
        <el-input size="medium" style="width: 200px;" v-model="selectCarPeoplePopKeyNumber"
          placeholder="根据手机号搜索"></el-input>
        <el-button size="medium" type="primary" @click="getSelectCarPeoplePopData">检索</el-button>
      </div>
      <span v-if="notFound" style="display: block;
    width: 100%;
    text-align: center;
    margin: 75px auto;
    font-size: 20px;
    cursor: pointer;" @click="goCreate">未检索到数据，点击创建车主用户账号</span>
      <div v-else class="popTableStyle">
        <el-table empty-text="请输入搜索条件进行检索" ref="selectCarPeoplePopTable" @current-change="selectCarPeoplePopChange"
          :data="selectCarPeoplePopData" style="width: 100%" height="200px" highlight-current-row>
          <el-table-column align="center" prop="customerName" label="姓名">
          </el-table-column>
          <el-table-column align="center" prop="phone" label="手机号码">
          </el-table-column>
        </el-table>
      </div>

      <el-divider></el-divider>
      <div slot="footer" style="display: flex;justify-content: space-evenly;align-items: center;height: 60px;">
        <el-button @click="selectCarPeoplePopShow = false">取 消</el-button>
        <el-button type="primary" @click="selectCarPeoplePopOk('selectCarPeoplePopTable')">确
          定</el-button>
      </div>

    </el-dialog>



    <!-- 分页器 -->
    <myPagination :pageNum="pageNum" :total="total" @PageChange="PageChange" @pageSizeChange="pageSizeChange">
    </myPagination>
  </div>
</template>





<script>
import MyUploadImgNotDetele from './../../../components/upload/MyUploadImgNotDetele.vue'

export default {
  components: {
    MyUploadImgNotDetele
  },
  data() {
    var plateNumberRules = (rule, value, callback) => {
      const regExp = /(^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$)/
      if (!regExp.test(value)) {
        return callback(new Error('请输入正确的车牌号码'));
      } else {
        callback()
      }
    };
    return {
      // 顶部筛选 ===================
      keyType: 'licensePlateNumber',
      keyWords: '',
      keyTime: ['', ''],
      //===================  顶部筛选 

      // 主要表格==================
      TableData: [], //用户数据
      pageNum: 1,
      pageSize: 10,
      total: 0,
      // ==================主要表格


      // 新增车辆======================
      UploadId: 0,
      ImgFileShow: false,
      EchoImgList1: [],
      EchoImgList2: [],
      deleteImg1: [],
      deleteImg2: [],
      AddCarPopScene: 'add',
      AddCarPopShow: false,
      insertForm: {},
      insertRules: {
        licensePlateNumber: [
          { required: true, message: '请输入车牌号', trigger: 'blur' },
          { validator: plateNumberRules, trigger: 'blur' }
        ],
        // brandModel: [
        //   { required: true, message: '请输入品牌型号', trigger: 'blur' },
        // ],
        // carType: [
        //   { required: true, message: '请选择车型', trigger: 'change' },
        // ],
        // carColor: [
        //   { required: true, message: '请输入车辆颜色', trigger: 'blur' },
        // ],
      },
      updateCascader: false,
      props: {
        lazy: true,
        lazyLoad: async (node, resolve) => {
          let { level } = node
          if (level == 3) {
            resolve([])
          } else {
            let res = await this.$api.car.myGetCarType(level * 1 + 1)
            if (res.code == 200) {
              let arr = []
              res.data.forEach(el => {
                arr.push({
                  label: el.name,
                  value: el.id,
                  leaf: level > 1
                })
              })
              resolve(arr)
            } else {
              this.$message.error(res.message)
            }

          }
        }
      },
      // =============================新增车辆

      // 选择车主========================
      notFound: false,
      selectCarPeoplePopShow: false,
      selectCarPeoplePopKeyName: '',
      selectCarPeoplePopKeyNumber: '',
      selectCarPeoplePopData: [],// 车主信息
      // ===========================选择车主


    };
  },
  async activated() {
    this.reset() // 重置清空 然后查询列表
  },
  methods: {
    carTypeChange(e) { //车型切换
      let data = this.$refs.cascader.getCheckedNodes()[0].pathLabels.join('')
      this.$set(this.insertForm, 'carType', data)
    },
    // 主要按钮 ===============================================================
    addClick() {
      this.AddCarPopScene = 'add'
      this.resetForm() //清空内容
      this.updateCascader = false
      // 初始化图片
      this.ImgFileShow = false
      this.UploadId = 0
      this.deleteImg1 = []
      this.deleteImg2 = []
      this.EchoImgList1 = []
      this.EchoImgList2 = []
      setTimeout(() => {
        this.ImgFileShow = true
      }, 50)

      this.AddCarPopShow = true
    },
    async updateClick(row) {
      this.AddCarPopScene = 'update'
      let res = await this.$api.car.myCarManageDetail(row.id)
      if (res.code == 200) {
        console.log(res.data, '详情');
        this.$set(this.insertForm, 'id', res.data.id)
        this.$set(this.insertForm, 'licensePlateNumber', res.data.licensePlateNumber)
        this.$set(this.insertForm, 'brandModel', res.data.brandModel)
        this.$set(this.insertForm, 'carType', res.data.carType)
        this.$set(this.insertForm, 'carTypeId', [])
        this.$set(this.insertForm, 'carColor', res.data.carColor)
        this.$set(this.insertForm, 'belongUserId', res.data.belongUserId)
        this.$set(this.insertForm, 'populationInformationName', res.data.name)
        this.$set(this.insertForm, 'carImageUrl', res.data.carImageUrl)
        this.$set(this.insertForm, 'pictureUrl', res.data.pictureUrl)

        this.$set(this.insertForm, 'hasCarSpace', res.data.hasCarSpace) //是否可以修改车主
        this.ImgFileShow = false
        this.UploadId = res.data.id
        this.deleteImg1 = []
        this.deleteImg2 = []

        if (res.data.carImageUrl) {
          this.EchoImgList1 = [res.data.carImageUrl]
        } else {
          this.EchoImgList1 = []
        }
        if (res.data.pictureUrl) {
          this.EchoImgList2 = [res.data.pictureUrl]
        } else {
          this.EchoImgList2 = []
        }

        setTimeout(() => {
          this.ImgFileShow = true
        }, 50)
      } else {
        this.$message.error(res.message)
      }
      this.updateCascader = true
      this.AddCarPopShow = true
    },
    detailClick(row) {
      this.$router.push(`/car/carDetail?id=${row.id}`)
    },
    deleteClick(row) {
      this.$confirm('此操作将永久删除该车辆, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let res = await this.$api.car.myCarManageDelete(row.id)
        if (res.code == 200) {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.getTableList()
        } else {
          this.$message.error(res.message)
        }
      })

    },
    //======================================================================主要按钮

    //新增车辆弹窗 ==============================================================
    okAddCarPop() { // 新增车辆弹窗 确认按钮
      this.$refs['insertForm'].validate((valid) => {
        if (valid) {
          // if (!this.insertForm.carImageUrl) {
          //   this.$message.error('请上传车辆照片')
          //   return
          // }
          if (!this.insertForm.belongUserId) {
            this.$message.error('请选择车主')
            return
          }
          this.$confirm('是否提交', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            // 删除图片
            this.deleteImg1.forEach(async el => {
              let res = await this.$api.ImgFile.delete(defaultUrl+'/business/carManage/deleteImg', {
                "picName": el
              })
            })
            this.deleteImg2.forEach(async el => {
              let res = await this.$api.ImgFile.delete(defaultUrl+'/business/carManage/deleteImg', {
                "picName": el
              })
            })

            let { licensePlateNumber, brandModel, carType, carColor, belongUserId, carImageUrl, pictureUrl } = this.insertForm

            switch (this.AddCarPopScene) {
              case 'add':
                let res = await this.$api.car.myCarManageInsert({
                  licensePlateNumber, //车牌号  参数都是必填项
                  brandModel, //品牌型号 
                  carType, //车型
                  carColor, //车辆颜色
                  belongUserId, //车主id
                  carImageUrl, //车辆图片url
                  pictureUrl
                })
                console.log(res, '新增车辆');
                if (res.code == 200) {
                  this.$message({
                    message: '新增成功',
                    type: 'success'
                  })
                  this.AddCarPopShow = false
                  this.getTableList()
                } else {
                  this.$message.error(res.message)
                }
                break
              case 'update':
                let updateRes = await this.$api.car.myCarManageUpdate({
                  id: this.insertForm.id,
                  brandModel, //品牌型号 
                  carType, //车型
                  carColor, //车辆颜色
                  belongUserId, //车主id
                  carImageUrl,
                  pictureUrl
                })
                console.log(updateRes, '修改车辆');
                if (updateRes.code == 200) {
                  this.$message({
                    message: '修改成功',
                    type: 'success'
                  })
                  this.AddCarPopShow = false
                  this.getTableList()
                } else {
                  this.$message.error(updateRes.message)
                }

                break
            }


          })
        }
      });
    },
    toSelectCarPeople() {
      this.selectCarPeoplePopShow = true
      this.selectCarPeoplePopKeyName = ''
      this.selectCarPeoplePopKeyNumber = ''
      this.notFound = false
      this.selectCarPeoplePopData = []
    },
    getImgList1(arr) {
      console.log(arr, '图片数据')
      this.$set(this.insertForm, 'carImageUrl', arr[0])
    },
    getImgList2(arr) {
      console.log(arr, '车位图片数据')
      this.$set(this.insertForm, 'pictureUrl', arr[0])
    },
    deleteImgList1(el) {
      this.deleteImg1.push(el)
    },
    deleteImgList2(el) {
      this.deleteImg2.push(el)
    },
    resetForm() { //清空新增车辆弹窗的输入框
      this.$set(this.insertForm, 'licensePlateNumber', '')
      this.$set(this.insertForm, 'brandModel', '')
      this.$set(this.insertForm, 'carType', '')
      this.$set(this.insertForm, 'carTypeId', [])
      this.$set(this.insertForm, 'carColor', '')
      this.$set(this.insertForm, 'belongUserId', '')
      this.$set(this.insertForm, 'populationInformationName', '')
      this.$set(this.insertForm, 'carImageUrl', '')
      this.$set(this.insertForm, 'pictureUrl', '')
      this.$set(this.insertForm, 'hasCarSpace', false) //是否可以修改车主
      this.$nextTick(() => {
        this.$refs.insertForm.clearValidate()
      })
    },

    // ================================================================新增车辆弹窗



    // 选择车主弹窗==============================================================
    goCreate() {
      this.$confirm('此操作将会跳转到用户管理页面?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.selectCarPeoplePopShow = false
        this.AddCarPopShow = false
        this.$router.push('/customerManag/List')
      }).catch(() => {

      });

    },
    async getSelectCarPeoplePopData() { //获取车主列表
      if (!this.selectCarPeoplePopKeyName && !this.selectCarPeoplePopKeyNumber) {
        this.$message.error('请输入检索条件')
        return
      }
      let res = await this.$api.car.myGetCustomerList({
        "name": this.selectCarPeoplePopKeyName, //客户姓名
        "phoneNumber": this.selectCarPeoplePopKeyNumber, //客户手机号
        "idNumber": "", //客户身份证号
        "pageSize": 1000,
        "pageNum": 1
      })
      console.log(res, 'qdqwd');
      if (res.code == 200) {
        if (res.data.list.length > 0) {
          this.notFound = false
          this.selectCarPeoplePopData = res.data.list
        } else {
          this.notFound = true
        }

      } else {
        this.$message.error(res.message)
      }
      // 然后判断是否之前选中过，然后激活
      this.selectCarPeoplePopData.forEach(el => {
        if (el.belongUserId == this.insertForm.belongUserId) {
          this.$nextTick(() => {
            this.$refs.selectCarPeoplePopTable.setCurrentRow(this.selectCarPeoplePopData[0])
          })
        }
      })

    },
    selectCarPeoplePopChange(val) { //单击车主事件
      console.log(val, '选中项');
    },
    selectCarPeoplePopOk(name) { // 选择车主确认按钮
      if (!this.$refs[name].store.states.currentRow) { //如果为空，提示未选择
        this.$message({
          message: '请选择车主',
          type: 'warning'
        });
      } else {
        // 获取当前表格选中项 this.$refs[name].store.states.currentRow
        if (this.$refs[name].store.states.currentRow) {
          this.$set(this.insertForm, 'belongUserId', this.$refs[name].store.states.currentRow.belongUserId)
          this.$set(this.insertForm, 'populationInformationName', this.$refs[name].store.states.currentRow.customerName)
        }

        this.selectCarPeoplePopShow = false
      }

    },
    // =================================================================选择车主弹窗

    // 选择车位弹窗==============================================================
    getSelectCarSpacePopData() { //获取车主列表
      //获取表格数据 selectCarSpacePopData

      // 然后判断是否之前选中过，然后激活
      // this.selectCarSpacePopData.forEach(el => {
      //   if (el.id ==???) {
      //     this.$nextTick(() => {
      //       this.$refs.selectCarSpacePopTable.setCurrentRow(this.selectCarSpacePopData[0])
      //     })
      //   }
      // })

    },
    selectCarSpacePopChange(val) { //单击车主事件
      console.log(val, '选中项');
    },
    selectCarSpacePopOk(name) { // 选择车主确认按钮

      // 获取当前表格选中项 this.$refs[name].store.states.currentRow
      // if (this.$refs[name].store.states.currentRow) {
      //    ???? = this.$refs[name].store.states.currentRow
      // }

      this.selectCarSpacePopShow = false
    },
    // =================================================================选择车位弹窗

    // 列表 =====================================================================
    PageChange(e) {//分页器——页数变化
      this.pageNum = e
      this.getTableList()
    },
    pageSizeChange(e) { //分页器——每页数量变化
      this.pageNum = 1
      this.pageSize = e
      this.getTableList()
    },
    SouSuo() {
      this.pageNum = 1
      this.getTableList()
    },
    reset() {
      this.pageNum = 1
      this.keyType = 'licensePlateNumber'
      this.keyWords = ''
      this.keyTime = ['', '']
      this.getTableList()
    },
    //按条件查询菜单列表
    async getTableList() {
      // return
      if (!this.keyTime) this.keyTime = ['', '']

      let res = await this.$api.car.getCarManageList({
        "start": this.keyTime[0], //创建开始时间  例：2024-09-12
        "end": this.keyTime[1], //创建结束时间  例：2024-09-12
        "type": this.keyType, //参数种类  车牌号：licensePlateNumber  车主名：name  手机号码：phoneNumber
        "keywords": this.keyWords, //关键字
        "pageSize": this.pageSize,
        "pageNum": this.pageNum
      })
      console.log(res, '车辆管理列表');
      if (res.code == 200) {
        if (res.data.list.length == 0 && this.pageNum != 1) {
          this.pageNum = 1
          this.getTableList()
          return
        }
        this.TableData = res.data.list;
        this.total = res.data.total;
      } else {
        this.$message.error(res.message)
      }

    },
    // ======================================================================列表

  },


};
</script>
<style scoped lang="less">
.tableBox {
  margin-top: 100px;

  /deep/ .el-table {
    .has-gutter {
      .is-leaf {
        background-color: #fafafa;
      }
    }
  }
}

.popTableStyle {
  /deep/ .el-table {
    .has-gutter {
      .is-leaf {
        background-color: #efefef;
      }
    }

    .el-table__body tr.current-row>td.el-table__cell {
      background-color: #409eff;

      .cell {
        color: white;
        font-weight: 600;
      }
    }
  }
}

.dialogStyle {
  /deep/ .el-dialog {
    border-radius: 20px;

    .el-dialog__body {
      padding: 0 20px;

      .el-divider {
        margin: 20px 0;
      }
    }
  }
}

.textBtn {
  position: relative;

  /deep/ .el-row {
    display: flex;
    justify-content: center;
  }

  .el {
    display: block;
    position: relative;

    &:nth-child(n+2) {

      // border-left: 1px solid #aaa;
      &::after {
        position: absolute;
        left: -1px;
        top: 50%;
        content: '';
        width: 2px;
        transform: translateY(-50%) scale(0.5, 1);
        height: 10px;
        background-color: #aaa;
      }
    }
  }
}



.Top {
  position: relative;

  .operation {
    position: absolute;
    left: 0;
    top: 68px;
  }
}
</style>